﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using zframe.loader;
using zframe;
using System.Linq;

public class LoadAssetBundleRemote : MonoBehaviour
{
    public Image abImg;
    public Image btnImg;

    // Start is called before the first frame update
    void Start()
    {
        string code = "你";

        int unicode = Char.ConvertToUtf32(code, 0); //获取字符的Unicode编码

        //把二进制数字转换成数字的过程
        byte[] bs = BitConverter.GetBytes(1000);   //UnicodeEncoding.Unicode.GetBytes(code);
        int tempCode = 0;
        for (int i = 0; i < bs.Length; i++)
        {
            int sub = bs[i];
            int addSub = (int)Math.Pow(256, i) * sub;
            tempCode += addSub;
        }

        ZLogger.Log("persistentDataPath=" + Application.persistentDataPath);
        ResManager.Instance.ResRoot = "http://127.0.0.1/u3d/abBuilds/";

        //ResManager.Instance.LoadAssetBundle("atlas_itembg.unity3d", OnBundleLoaded);
        //ResManager.Instance.LoadAssetBundle("atlas_button.unity3d", OnBundleLoaded);
        //ResManager.Instance.LoadAssetBundle("atlas_scale9img.unity3d", OnBundleLoaded);
        //ResManager.Instance.LoadAssetBundle("atlas_scale9img_dd.unity3d", OnBundleLoaded);

        ZLogger.Log("开始测试加载...now="+DateTimeOffset.Now.ToUnixTimeMilliseconds());
        /*
        ResManager.Instance.LoadAssetBundles(new string[] { "atlas_itembg.unity3d", "atlas_button.unity3d"
        ,"atlas_scale9img.unity3d","atlas_scale9img_dd.unity3d"}, OnBundlesLoaded);
        */

        TestLoadAbAndWrite();

        //另外一种下载方式，通过协程方式下载
        StartCoroutine(customDown());

        ZLogger.Error("LoadAssetBundleRemote 测试错误输出..");
        ZLogger.Warning("LoadAssetBundleRemote 测试警告输出..");

        //Application.logMessageReceived += Application_logMessageReceived;

        

    }

    private void Application_logMessageReceived(string condition, string stackTrace, LogType type)
    {
        ZLogger.Log("Application_logMessageReceived=" + condition+ "stackTrace="+ stackTrace);
    }

    IEnumerator customDown()
    {
        string abName = "atlas_button.unity3d";
        string url = ResManager.Instance.GetUrl(abName);
        UnityWebRequest customReq = new UnityWebRequest(url);
        byte[] buffer = new byte[1024*1024]; //传入特定的buff对象可以节省内存 但是必须要有足够的长度
        //CustomerDownloadHandler customHandler = new CustomerDownloadHandler(buffer);
        CustomerDownloadHandler customHandler = new CustomerDownloadHandler();
        customReq.downloadHandler = customHandler;
        yield return customReq.SendWebRequest(); //通过协程下载 等待下载完成再处理

        if (!customReq.isHttpError && !customReq.isNetworkError) //没有错误下载完成
        {
            ZLogger.Log("customDown CustomerDownloadHandler customHandler" + customHandler.data);
            AssetBundle ab = AssetBundle.LoadFromMemory(customHandler.data);
            Sprite sp = ab.LoadAsset<Sprite>("common_btn_01");
            btnImg.sprite = sp;
        }

    }

    private void TestLoadAbAndWrite()
    {
        //通过默认加载器加载
        string abName = "atlas_itembg.unity3d";
        UnityWebRequest request = UnityWebRequest.Get(ResManager.Instance.GetUrl(abName));
        UnityWebRequestAsyncOperation opt = request.SendWebRequest();
        opt.completed += (AsyncOperation optArg) =>
        {
            if (request.isHttpError || request.isNetworkError)
            {
                ZLogger.Log("网络错误 request.error=" + request.error);
                return;
            }
            //加载完成后构建ab包
            ZLogger.Log("=" + request.downloadHandler.data);
            string fileName = Path.Combine(Application.persistentDataPath, "assetbundles", abName);
            /*
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            */
            File.WriteAllBytes(fileName, request.downloadHandler.data); //写入本地文件
            AssetBundle ab = AssetBundle.LoadFromFile(fileName); //再从文件读取构建，进一步实现热更新操作
            Texture2D tex = ab.LoadAsset<Texture2D>("04hong");
            var sp = Sprite.Create(tex,new Rect(0,0, tex.width, tex.height),new Vector2(0,0));
            abImg.sprite = sp;
            //AssetBundle.LoadFromMemory(request.downloadHandler.data); //也可以直接通过二进制数据构建
            ZLogger.Log("=" + ab.name + "fileName=" + fileName);
        };
    }

    private void OnBundleLoaded(UnityEngine.Object asset,BaseResLoader loader)
    {
        AssetBundle bundle = (AssetBundle)asset;
        bool flag = bundle == null;
        ZLogger.Log("++++++ OnBundleLoaded bundle=" + flag);
    }

    private void OnBundlesLoaded(UnityEngine.Object[] assets)
    {
        ZLogger.Log("OnBundlesLoaded="+ assets.Length);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
